package de.midnightdance.admin;

import org.eclipse.equinox.app.IApplication;
import org.eclipse.equinox.app.IApplicationContext;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.PlatformUI;

import de.midnightdance.admin.ui.logIn.UserLoginDialog;
import de.midnightdance.admin.ws.entities.RequiemUser;

/**
 * This class controls all aspects of the application's execution
 */
public class ApplicationClientAdmin implements IApplication {
	private static boolean USE_AUTHENTICATION = false;
	/* (non-Javadoc)
	 * @see org.eclipse.equinox.app.IApplication#start(org.eclipse.equinox.app.IApplicationContext)
	 */
	public Object start(IApplicationContext context) throws Exception {
		Display display = PlatformUI.createDisplay();
		boolean authenticated = false;
		try {
			if(USE_AUTHENTICATION){
				// use authentication
				authenticated = authenticate(display);
			}else{
				authenticated = true;
			}
			// 	
			if (authenticated) {	
				int returnCode = PlatformUI.createAndRunWorkbench(display, new ApplicationWorkbenchAdvisor());
				if (returnCode == PlatformUI.RETURN_RESTART)
					return IApplication.EXIT_RESTART;
				else
					return IApplication.EXIT_OK;
			}else{
				return IApplication.EXIT_OK;
			}
		} finally {
			display.dispose();
		}
		
	}

	/* (non-Javadoc)
	 * @see org.eclipse.equinox.app.IApplication#stop()
	 */
	public void stop() {
		if (!PlatformUI.isWorkbenchRunning())
			return;
		final IWorkbench workbench = PlatformUI.getWorkbench();
		final Display display = workbench.getDisplay();
		display.syncExec(new Runnable() {
			public void run() {
				if (!display.isDisposed())
					workbench.close();
			}
		});
	}
	 
	private boolean authenticate(Display display) {
		UserLoginDialog loginDialog = new UserLoginDialog(display);
		loginDialog.openShell();
		RequiemUser user = loginDialog.getUser();
		Activator.getDefault().setLoggedUser(user);
		return user != null;		
	}

}
